<template>
  <!-- 安全管理网络 -->
  <div class="mgrgrid">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >

        <!-- 左上方菜单栏 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.mgrgrid_delete"
            @click="handleDelete">
            删 除
          </el-button>
          <el-button
            type="success"
            size="small"
            icon="el-icon-picture-outline"
            plain
            @click="handleDiagram">
            架构图
          </el-button>
        </template>

        <template slot-scope="scope" slot="menu">
          <el-button
            type="text"
            icon="el-icon-circle-plus-outline"
            size="small"
            @click="handleAdd(scope.row,scope.index)">
            新增子项
          </el-button>
        </template>
        
      </avue-crud>

      <!-- 架构图 -->
      <el-dialog 
        title="架构图"
        append-to-body
        :visible.sync="diagramDialog"
        :close-on-click-modal="false" 
        :before-close="closeDiagramDialog"
        width="70%"
        class="diagram_dialog"
      >

        <!-- 架构图 -->
        <div class="diagram_container">
          <vue2-org-tree 
            :data="treeData"
            collapsable
            @on-expand="onExpand" 
            @on-node-click="NodeClick" />
        </div>

        <div v-show="basicSwich" class="floating">
          <el-button type="text" icon="el-icon-close" @click="closeBasicInfo()"></el-button>
          <p>名称: {{basicInfo.mc}}</p>
          <p>责任人: {{basicInfo.fzren}}</p>
          <p>联系方式: {{basicInfo.fzrlxfs}}</p>
          <span>主要职责: {{basicInfo.aqzz}}</span>
        </div>

        <!-- 按钮 -->
        <div class="diagram_footer">
          <el-button 
            type="primary"
            size="small"
            @click="closeDiagramDialog()">
            关 闭
          </el-button>
        </div>

      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove
} from "@/api/duty/dutiesandresponsibilities/mgrgrid";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        index: false,
        selection: true,
        viewBtn: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 300,
        defaultExpandAll: true,
        column: [
          {
            label: "名称",
            prop: "mc",
            rules: [{
              required: true,
              message: "请输入名称",
              trigger: "blur"
            }]
          },
          {
            label: "所属上级",
            prop: "parentId",
            hide: true,
            type: "tree",
            dicData: [],
            props: {
              label: "mc",
              value: "id"
            }
          },
          {
            label: "负责人",
            prop: "fzren",
            align: "center",
            rules: [{
              required: true,
              message: "请输入负责人",
              trigger: "blur"
            }]
          },
          {
            label: "联系方式",
            prop: "fzrlxfs",
            align: "center",
            rules: [{
              required: true,
              message: "请输入负责人联系方式",
              trigger: "blur"
            }]
          },
          {
            label: "安全职责",
            prop: "aqzz",
            hide: true,
            span: 24,
            type: "textarea",
            maxLength: 150,
            rules: [{
              required: true,
              message: "请输入安全职责",
              trigger: "blur"
            }]
          },
          {
            label: "备注",
            prop: "bz",
            align: "center",
            span: 24,
            type: "textarea",
            maxLength: 150
          }
        ]
      },
      // 弹窗架构图
      diagramDialog: false,
      treeData: {},
      basicSwich: false,
      basicInfo: {
        mc: null,
        fzren: null,
        fzrlxfs: null,
        aqzz: null
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.mgrgrid_add, false),
        viewBtn: this.vaildData(this.permission.mgrgrid_view, false),
        delBtn: this.vaildData(this.permission.mgrgrid_delete, false),
        editBtn: this.vaildData(this.permission.mgrgrid_edit, false)
      };
    },

    // 勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  watch: {
    data() {
      if(JSON.stringify(this.data) !== "{}" &&JSON.stringify(this.data) !== "[]") {
        this.initData();
      }
    }
  },
  mounted() {
    this.initData();
  },
  methods: {

    // 初始化数据
    initData(){
      getList().then(res => {
        const parentColumn = this.findObject(this.option.column, "parentId");
        parentColumn.dicData = res.data.data;
        this.treeData = this.formatTreeData(res.data.data[0]);
      });
    },

    // 格式化架构图数据
    formatTreeData(row) {
      var treeData = {
        id: row.id,
        label: row.mc + ":\n" + row.fzren
      };
      if(row.children && row.children.length > 0) {
        treeData["children"] = [];
        row.children.forEach(item => {
          var child = this.formatTreeData(item);
          treeData.children.push(child);
        });
      }
      return treeData;
    },

    // 新增
    rowSave(row, done, loading) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.parentId = row.parentId === undefined || row.parentId === "" ? 0 : row.parentId;
      add(row).then(
        () => {
          this.onLoad();
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },

    // 修改
    rowUpdate(row, index, done, loading) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.parentId = row.parentId === undefined || row.parentId === "" ? 0 : row.parentId;
      update(row).then(
        () => {
          this.onLoad();
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad();
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad();
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开编辑、新增、查看弹窗前
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad();
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.onLoad(params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.query);
    },

    // 加载数据
    onLoad(params = {}) {
      this.loading = true;
      getList(Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.data = data;
        this.loading = false;
        this.selectionClear();
      });
    },

    // 新增子项
    handleAdd(row) {
      this.$refs.crud.value.parentId = row.id;
      this.$refs.crud.option.column.filter(item => {
        if (item.prop === "parentId") {
          item.value = row.id;
          item.addDisabled = true;
        }
      });
      this.$refs.crud.rowAdd();
    },

    /**
     * 弹窗：架构图
    */

    // 打开架构图弹窗
    handleDiagram() {
      this.diagramDialog = true;
      this.toggleExpand(this.treeData, true);
    },

    // 关闭、取消架构图弹窗
    closeDiagramDialog() {
      this.diagramDialog = false;
    },

    // 折叠
    collapse(list) {
      var _this = this;
      list.forEach(function(child) {
        if (child.expand) {
          child.expand = false;
        }
        child.children && _this.collapse(child.children);
      });
    },

    // 打开
    onExpand(e, data) {
      if ("expand" in data) {
        data.expand = !data.expand;
        if (!data.expand && data.children) {
          this.collapse(data.children);
        }
      } else {
        this.$set(data, "expand", true);
      }
    },

    // 默认展开
    toggleExpand(data, val) {
      var _this = this;
      if (Array.isArray(data)) {
        data.forEach(function(item) {
          _this.$set(item, "expand", val);
          if (item.children) {
            _this.toggleExpand(item.children, val);
          }
        });
      } else {
        this.$set(data, "expand", val);
        if (data.children) {
          _this.toggleExpand(data.children, val);
        }
      }
    },

    // 点击事件
    NodeClick(e,data){
      getDetail(data.id).then(res => {
        this.basicInfo = this.formatBasicInfo(res.data.data);
      }).then(() => {
        var containerEle = document.getElementsByClassName('diagram_dialog')[0];
        var dialogEle = containerEle.getElementsByClassName("el-dialog")[0];
        var floating = document.getElementsByClassName('floating')[0];
        let widthProportion = dialogEle.clientWidth / window.innerWidth;
        let heightProportion = dialogEle.clientHeight / window.innerHeight;
        floating.style.left = parseInt(e.clientX * widthProportion) + 'px';
        floating.style.top = parseInt(e.clientY * heightProportion) + 'px';
        this.basicSwich = true;
      });
    },

    // 格式化弹窗数据
    formatBasicInfo(resData) {
      var data = {
        mc: resData.mc,
        fzren: resData.fzren,
        fzrlxfs: resData.fzrlxfs,
        aqzz: resData.aqzz
      };
      return data;
    },

    // 关闭基本信息框
    closeBasicInfo() {
      this.basicSwich = false;
    }

  }
};
</script>

<style lang="scss">
.diagram_dialog {
  .org-tree-node-label {
    color: #fff;
    background-color: #3a8ee6;
    cursor: pointer;

    .org-tree-node-label-inner {
      white-space: pre;
    }
  }
}
</style>

<style lang="scss" scoped>
.diagram_dialog {
  .diagram_container {
    text-align: center;
    overflow-x: auto;
    overflow-y: auto;
    width: 100%;
    max-height: 500px;
  }
}

.diagram_footer {
  text-align: center;
  margin-top: 15px;

  .el-button {
    width: 100px;
    height: 35px;
  }
}

.floating{
  background: rgba(0, 0, 0, 0.7);
  width: 260px;
  position: absolute;
  color: #fff;
  padding: 15px;
  border-radius: 15px;
  box-sizing: border-box;
  left:0;
  top: 0;
  transition: all 0.3s;
  z-index: 999;
  text-align: left;
  font-size: 12px;

  p {
    margin-top: 0px;
    margin-bottom: 5px;
    text-align: center;
    font-size: small;
    font-weight: 600;
  }

  .el-button {
    color: white;
    font-size: medium;
    position: absolute;
    right: 15px;
    top: 2px;
  }
}
</style>